<?php
namespace app\home\controller;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Exception;

/*
 * 权限代码
 * 4:系统管理员
 * 3：资产管理员
 * 2：实验室主任
 * 1：实验员
 * 0：授权用户
*/
class Material extends Controller
{
    function authid_to_name($authority)   //用户权限id转权限名字
    {
        switch ($authority){
            case 4:
                return '系统管理员';
                break;
            case 3:
                return '资产管理员';
                break;
            case 2:
                return '实验室主任';
                break;
            case 1:
                return '实验员';
                break;
            case 0:
                return '授权用户';
                break;
        }
    }
    function authority($array){
        $cookie=new Cookie();
        $safecode=$cookie->get('safecode');
        $user_data=Db::name('user')->where('safecode',$safecode)->find();
        $authority_id=$user_data['authority'];
        if(!in_array($authority_id,$array)){
            $this->error('无权访问','../Index/home');
            exit();
        }
    }
    ///////////////////导出//////////////////
    public function export_material_data()     //导出耗材信息
    {
        $this->authority([4,3,2]);
        $material = Db::name('repertory');
        $list = $material->select();
        $objPHPExcel = new \PHPExcel();
        // 设置sheet
        $objPHPExcel->setActiveSheetIndex(0);
        // 设置列的宽度
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(40);
        // 设置表头
        $objPHPExcel->getActiveSheet()->SetCellValue('A1', '耗材编号');
        $objPHPExcel->getActiveSheet()->SetCellValue('B1', '耗材名称');
        $objPHPExcel->getActiveSheet()->SetCellValue('C1', '耗材型号');
        $objPHPExcel->getActiveSheet()->SetCellValue('D1', '耗材数量');
        $objPHPExcel->getActiveSheet()->SetCellValue('E1', '备注');
        //存取数据
        $num = 2;
        foreach ($list as $k => $v) {
            $objPHPExcel->getActiveSheet()->SetCellValue('A' . $num, $v['material_id']);
            $objPHPExcel->getActiveSheet()->SetCellValue('B' . $num, $v['material_name']);
            $objPHPExcel->getActiveSheet()->SetCellValue('C' . $num, $v['material_model']);
            $objPHPExcel->getActiveSheet()->SetCellValue('D' . $num, $v['num']);
            $objPHPExcel->getActiveSheet()->SetCellValue('E' . $num, $v['comment']);
            $num++;
        }
        // 文件名称
        $fileName = "耗材信息" . date('Y-m-d', time()) . rand(1, 1000);
        $xlsName = iconv('utf-8', 'gb2312', $fileName);
        // 设置工作表名
        $objPHPExcel->getActiveSheet()->setTitle('sheet');
        //下载 excel5与excel2007
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        ob_end_clean();     // 清除缓冲区,避免乱码
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl;charset=UTF-8");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header("Content-Disposition:attachment;filename=" . $xlsName . ".xlsx");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save("php://output");

    }
    ///////////////购买申请////////////////
    public function apply_purchase() //耗材购买申请  权限：4,2,0
    {
        $this->authority([4,2,0]);
        $cookie=new Cookie();
        $safecode=$cookie->get('safecode');
        $user_data=Db::name('user')->where('safecode',$safecode)->find();
        if(input('post.')){
            $material_name=input('post.material_name');
            $material_model=input('post.material_model');
            $material_num=input('post.num');
            $applicant_id=$user_data['uid'];
            $applicant=$user_data['name'];
            $apply_time=date(('Y-m-d H:i:s'),time());
            if(Db::name('apply')->insert([
                'material_name'=>$material_name,
                'material_model'=>$material_model,
                'material_num'=>$material_num,
                'applicant_id'=>$applicant_id,
                'applicant'=>$applicant,
                'apply_time'=>$apply_time
            ])){
                $this->assign('msg','申请成功，请耐心等待审核完成');
                $this->assign('url','apply_purchase');
                return $this->fetch('do_success',[],['__PUBLIC__'=>'/public/static']);
            }else{
                $this->assign('msg','出错了，请联系管理员');
                $this->assign('url','apply_purchase');
                return $this->fetch('do_error',[],['__PUBLIC__'=>'/public/static']);
            }
        }
        $this->assign('user',$user_data);
        return $this->fetch('apply_purchase',[],['__PUBLIC__'=>'/public/static']);
    }
    public function material_name()  //返回json格式材料名称
    {
        $this->authority([4,2,0]);
        $name=input('get.name');
        $material_data=Db::name('repertory')->where('material_name','like','%'.$name.'%')->limit(10)->select();
        $arr=array();
        foreach ($material_data as $one_data){
            $arr[]=[
                'id'=>$one_data['material_id'],
                'model'=>$one_data['material_model'],
                'name'=>$one_data['material_name']
            ];

        }
        $arr2=[
            'message'=>'',
            'value'=>$arr,
            'code'=>200,
            'redirect'=>''
        ];
        return json($arr2);
    }
    public function material_model()  //返回json格式材料规格
    {
        $this->authority([4,2,0]);
        $name=input('get.name');
        $model=input('get.model');
        $material_data=Db::name('repertory')->where('material_model','like','%'.$model.'%')->where('material_name','=',$name)->limit(10)->select();
        $arr=array();
        foreach ($material_data as $one_data){
            $arr[]=[
                'id'=>$one_data['material_id'],
                'model'=>$one_data['material_model'],
                'name'=>$one_data['material_name']
            ];

        }
        $arr2=[
            'message'=>'',
            'value'=>$arr,
            'code'=>200,
            'redirect'=>''
        ];
        return json($arr2);
    }
    public function material_list()     //当前用户申请列表
    {
        $this->authority([4,2,0]);
        $cookie=new Cookie();
        $safecode=$cookie->get('safecode');
        $user_data=Db::name('user')->where('safecode',$safecode)->find();
        $this->assign('user',$user_data);
        return $this->fetch('material_list',[],['__PUBLIC__'=>'/public/static']);

    }
    public function material_list_json()    //当前用户申请的列表的json数据接口
    {
        $this->authority([4,2,0]);
        $cookie=new Cookie();
        $safecode=$cookie->get('safecode');
        $user_data=Db::name('user')->where('safecode',$safecode)->find();
        $uid=$user_data['uid'];
        $user_apply_data=Db::name('apply')->where('applicant_id',$uid)->select();
        return json($user_apply_data);
    }
    ////////////审核申请//////////////////
    public function check_purchase()    //审核购买申请
    {
        $this->authority([4,2]);
        return $this->fetch('check_purchase',[],['__PUBLIC__'=>'/public/static']);
    }
    public function all_material_list_json()    //所有用户的申请列表
    {
        $this->authority([4,2]);
        $user_apply_data=Db::name('apply')->order('approval_status','asc')->select();
        return json($user_apply_data);
    }
    public function pass_all_apply()    //通过所有提交的审核
    {
        $this->authority([4,2]);
        $in_data=file_get_contents('php://input');
        $data=json_decode($in_data,true);
        $success=0;
        $error=0;
        foreach ($data as $datum) {
            $apply_id=$datum['apply_id'];
            $apply_data=Db::name('apply')->where('apply_id',$apply_id)->find();
            if($apply_data['approval_status']=='0'){
                if(Db::name('apply')->where('apply_id',$apply_id)->update(['approval_status'=>'1'])){
                    $material=Db::name('apply')->where('apply_id',$apply_id)->find();
                    $material_name=$material['material_name'];
                    $material_model=$material['material_model'];
                    $result=Db::name('repertory')->where(['material_name'=>$material_name,'material_model'=>$material_model])->find();
                    if(empty($result)){
                        if(Db::name('repertory')->insert(['material_name'=>$material_name,'material_model'=>$material_model,'num'=>0])){
                            $success++;
                        }else{
                            $error++;
                        }
                    }else{
                        $success++;
                    }
                    $material_result=Db::name('repertory')->where(['material_name'=>$material_name,'material_model'=>$material_model])->find();
                    try{
                        Db::name('purchase')->insert([
                            'material_name'=>$material_name,
                            'material_model'=>$material_model,
                            'material_num'=>$material['material_num'],
                            'material_id'=>$material_result['material_id'],
                            'apply_id'=>$apply_id
                        ]);
                    }catch (\Exception $e){
                        $error++;
                    }
                }else{
                    $error++;
                }
            }else{
                $error++;
            }

        }
        $arr=[
            'success'=>$success,
            'error'=>$error
        ];
        return json($arr);
    }
    public function fail_all_apply()    //驳回所有提交的审核
    {
        $this->authority([4,2]);
        $in_data=file_get_contents('php://input');
        $data=json_decode($in_data,true);
        $success=0;
        $error=0;
        foreach ($data as $datum) {
            $apply_id=$datum['apply_id'];
            $apply_data=Db::name('apply')->where('apply_id',$apply_id)->find();
            if($apply_data['approval_status']=='0')         //如果状态为审核中
            {
                if(Db::name('apply')->where('apply_id',$apply_id)->update(['approval_status'=>'2'])){
                    $success++;
                }else{
                    $error++;
                }
            }else{
                $error++;
            }

        }
        $arr=[
            'success'=>$success,
            'error'=>$error
        ];
        return json($arr);
    }
    ///////////////////////耗材入库//////////////////////
    public function into_repertory() //耗材入库  权限：4,3
    {
        $this->authority([4,3]);
        return $this->fetch('into_repertory',[],['__PUBLIC__'=>'/public/static']);
    }
    public function purchase_json() //购置列表
    {
        $this->authority([4,3]);
        return json(Db::name('purchase')->order('status','desc')->select());
    }
    public function into()  //耗材入库
    {
        $this->authority([4,3]);
        if(input('get.')){
            $purchase=Db::name('purchase')->where('Id',input('get.Id'))->find();
            $cookie=new Cookie();
            $safeocode=$cookie->get('safecode');
            $user=Db::name('user')->where('safecode',$safeocode)->find();
            if(input('post.')){
                $Id=input('get.Id');
                $get_num=input('post.get_num');
                $unit_price=input('post.unit_price');
                $purchaser_id=$user['uid'];
                $purchaser=input('post.purchaser');
                $purchase_time=input('post.purchase_time');
                $comment=input('post.comment');

                if((int)$get_num>=(int)$purchase['material_num']){
                    $purchase_status=1;
                    $apply_status=3;
                }else{
                    $purchase_status=2;
                    $apply_status=4;
                }
                $apply_data=Db::name('apply')->where('apply_id',$purchase['apply_id'])->find();
                if($apply_data['approval_status']=='1'){
                    try{
                        Db::name('purchase')->where('Id',$Id)->update([
                            'get_num'=>$get_num,
                            'material_unit_price'=>$unit_price,
                            'purchaser_id'=>$purchaser_id,
                            'purchaser'=>$purchaser,
                            'purchase_time'=>$purchase_time,
                            'comment'=>$comment,
                            'status'=>$purchase_status
                        ]);
                        Db::name('apply')->where('apply_id',$purchase['apply_id'])->update([
                            'approval_status'=>$apply_status
                        ]);
                        Db::name('repertory')
                            ->where('material_id',$purchase['material_id'])
                            ->setInc('num',(int)$get_num);
                    }catch (\Exception $e){
                        $this->assign('msg',$e);
                        return $this->fetch('do_error',[],['__PUBLIC__'=>'/public/static']);
                    }
                    $this->assign('msg','操作成功');
                    return $this->fetch('do_success',[],['__PUBLIC__'=>'/public/static']);
                }else{
                    $this->assign('msg','目前的申请状态不允许入库');
                    return $this->fetch('do_error',[],['__PUBLIC__'=>'/public/static']);
                }

            }
            $this->assign('purchase',$purchase);
            $this->assign('user',$user);
            return $this->fetch('into',[],['__PUBLIC__'=>'/public/static']);
        }else{
            $this->error('非法访问');
        }
    }
    //////////////////////
    public function receive_material() //耗材领取  权限：4,3，2,0
    {
        $this->authority([4,3,2,1,0]);
        $cookie=new Cookie();
        $safecode=$cookie->get('safecode');
        $user=Db::name('user')->where('safecode',$safecode)->find();
        if(input('post.')){
            $approval_status=0;
            $material_name=input('post.material_name');
            $material_model=input('post.material_model');
            $use_area=input('post.use_area');
            $num=input('post.num');
            $user_id=$user['uid'];
            $user_name=$user['name'];
            $receive_time=date("Y-m-d H:i:s",time());
            $search_result=Db::name('repertory')
                ->where('material_name',$material_name)
                ->where('material_model',$material_model)
                ->where('num','>=',$num)
                ->find();
            if(!empty($search_result)){
                if(Db::name('use')->insert([
                    'material_name'=>$material_name,
                    'material_id'=>$search_result['material_id'],
                    'num'=>$num,
                    'use_area'=>$use_area,
                    'user_id'=>$user_id,
                    'user'=>$user_name,
                    'receive_time'=>$receive_time,
                    'material_model'=>$material_model
                ])){
                    $this->assign('msg','申请成功，请耐心等待');
                    return $this->fetch('do_success',[],['__PUBLIC__'=>'/public/static']);
                }
            }else{
                $this->error('库存不足，正在跳转到申购页面','apply_purchase');
            }
        }
        $this->assign('user',$user);
        return $this->fetch('receive',[],['__PUBLIC__'=>'/public/static']);
    }
    public function check_receive() //耗材领取审核    权限4,2
    {
        return $this->fetch('check_receive',[],['__PUBLIC__'=>'/public/static']);
    }
    public function receive_apply_json(){
        $this->authority([4,2]);
        return json(Db::name('use')->order('approval_status','desc')->select());
    }
    public function receive_list_json() //当前用户申领记录
    {
        $cookie=new Cookie();
        $safecode=$cookie->get('safecode');
        $user_data=Db::name('user')->where('safecode',$safecode)->find();
        $uid=$user_data['uid'];
        return json(Db::name('use')->where('user_id',$uid)->select());
    }
    public function pass_list_json()
    {
        $this->authority([4,3]);
        return json(Db::name('use')->where('approval_status','<>','2')->where('approval_status','<>','0')->select());
    }
    public function receive_list()
    {
        return $this->fetch('receive_list',[],['__PUBLIC__'=>'/public/static']);
    }
    public function pass_all_receive()  //通过所有领取申请
    {
        $this->authority([4,2]);
        $in_data=file_get_contents('php://input');
        $data=json_decode($in_data,true);
        $success=0;
        $error=0;
        foreach ($data as $datum) {
            $apply_id=$datum['Id'];
            $apply_data=Db::name('use')->where('Id',$apply_id)->find();
            if($apply_data['approval_status']=='0')     //  确保状态为审核中
            {
                if(Db::name('use')->where('Id',$apply_id)->update(['approval_status'=>'1'])){
                    $success++;
                }else{
                    $error++;
                }
            }else{
                $error++;
            }

        }
        $arr=[
            'success'=>$success,
            'error'=>$error
        ];
        return json($arr);
    }
    public function fail_all_receive()  //通过所有领取申请
    {
        $this->authority([4,2]);
        $in_data=file_get_contents('php://input');
        $data=json_decode($in_data,true);
        $success=0;
        $error=0;
        foreach ($data as $datum) {
            $apply_id=$datum['Id'];
            $apply_data=Db::name('use')->where('Id',$apply_id)->find();
            if($apply_data['approval_status']=='0')     //  确保状态为审核中
            {
                if(Db::name('use')->where('Id',$apply_id)->update(['approval_status'=>'2'])){
                    $success++;
                }else{
                    $error++;
                }
            }else{
                $error++;
            }
        }
        $arr=[
            'success'=>$success,
            'error'=>$error
        ];
        return json($arr);
    }
    public function disturb_material()  //分发耗材
    {
        $this->authority([4,3]);
        return $this->fetch('disturb_material',[],['__PUBLIC__'=>'/public/static']);
    }
    public function disturb()   //分发操作
    {
        $this->authority([4,3]);
        $in_data=file_get_contents('php://input');
        $data=json_decode($in_data,true);
        $success=0;
        $error=0;
        $is_enough=1;
        foreach ($data as $datum) {
            $apply_id=$datum['Id'];
            $apply_data=Db::name('use')->where('Id',$apply_id)->find();
            if($apply_data['approval_status']=='1')     //  确保状态为审核通过
            {
                if(Db::name('use')->where('Id',$apply_id)->update(['approval_status'=>'3'])){
                    $receive_data=Db::name('use')->where('Id',$apply_id)->find();
                    $repertory_data=Db::name('repertory')->where('material_id',$receive_data['material_id'])->find();
                    if((int)$repertory_data['num']>=(int)$receive_data['num']){
                        try{
                            Db::name('repertory')->where('material_id',$receive_data['material_id'])->dec('num',(int)$receive_data['num'])->update();
                            $success++;
                        }catch(\Exception $e){
                            $error++;
                        }
                    }else{
                        $is_enough=0;
                        $error++;
                    }
                }else{
                    $error++;
                }
            }else{
                $error++;
            }

        }
        $arr=[
            'success'=>$success,
            'error'=>$error,
            'is_enough'=>(int)$is_enough
        ];
        return json($arr);
    }
    /////////////////////查看耗材信息/////////////////
    public function material_look() //查看耗材信息
    {
        $this->authority([4,3,2]);
        if(input('get.')){
            $material_id=input('get.material_id');
            $material_data=Db::name('repertory')->where('material_id',$material_id)->find();
            $this->assign('material',$material_data);
            return $this->fetch('material_look',[],['__PUBLIC__'=>'/public/static']);
        }else{
            $this->error('非法访问');
        }

    }
    public function material_json() //耗材json数据
    {
        $this->authority([4,3,2]);
        $material_data=Db::name('repertory')->select();
        return json($material_data);
    }
    public function search_material() //耗材信息查询  权限：4,3，2
    {
        $this->authority([4,3,2]);
        $cookie=new Cookie();
        $safecode=$cookie->get('safecode');
        $user_data=Db::name('user')->where('safecode',$safecode)->find();
        $this->assign('user',$user_data);
        return $this->fetch('search_material',[],['__PUBLIC__'=>'/public/static']);
    }
}
